package com.wz.dhs.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;
import java.util.Objects;

/**
 * 国际化工具类
 */
@Component
public class MessageUtils implements ApplicationContextAware {


    private static MessageSource messageSource;


    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        try {
            return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale() == null ? Locale.SIMPLIFIED_CHINESE : LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return msgKey;
        }
    }

    /**
     * 获取单个国际化翻译值,有中文走中文，其他默认返回原文
     */
    public static String get(String code,String message) {
        try {
            if(Objects.nonNull(LocaleContextHolder.getLocale()) && LocaleContextHolder.getLocale().equals(Locale.SIMPLIFIED_CHINESE)){
                //中文
                String info = messageSource.getMessage(code,null,Locale.SIMPLIFIED_CHINESE);
                return Objects.isNull(info) ? message : info;
            }
            return message;
        } catch (Exception e) {
            return message;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//        LocaleContextHolder.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        MessageSource bean = applicationContext.getBean(MessageSource.class);
        messageSource = bean;
    }
}
